<html>
<head>
<title>ttcloud</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel='stylesheet' type="text/css" href="../../../extjs-4.1.0/resources/css/ext-all-gray.css"/>
<script type="text/javascript" src="../../../extjs-4.1.0/ext-all.js"></script>
<script type="text/javascript" src="../../../js/head.js"></script>
<script type="text/javascript" src="../../../js/ux/form/SearchField.js"></script>
<script src="../../../js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8" src="../../../js/i18n.js"></script>
<style type="text/css">
 #ext-quicktips-tip-body{
 word-break:break-all;
 word-wrap:break-word;
 }
</style>
<script>
	Ext.onReady(function() {          //     
				var params;
				var flag=true;
				MultiLang = (function() {
					return {
						init : function() {
							params = getCookie("lang");
							i18n.set({
								lang : params,
								path : '../../../resources'
							});
							if (params) {
								var url = Ext.util.Format
										.format(
												'../../../extjs-4.1.0/locale/ext-lang-{0}.js',
												params);
								Ext.Ajax.request({
									url : url,
									success : this.onLoadExtLocaleSuccess,
									failure : this.onLoadExtLocaleFailure,
									scope : this
								});
							} else {
								// no language found, locale of ExtJS will be english as default
								//this.loadmyprojectLocale();
								this.setup();
							}
						},
						onLoadExtLocaleSuccess : function(response) {
							try {
								eval(response.responseText);
							} catch (e) {
								//Ext.Msg.alert('Failure', e.toString());
							}
							//this.loadmyprojectLocale();
							this.setup();
						},
						onLoadExtLocaleFailure : function() {
							//Ext.Msg.alert('Failure','Failed to load locale file.');
							this.setup();
							//this.loadmyprojectLocale();
						},
						setup : function() {
/*********************************************页面渲染开始******************************************************************/

function convertboolean(v, record){
	if(v){
		return i18n._('Yes');
	}
	return i18n._('No');
}

//定义ZoneGroup
Ext.define('ZoneGroup',{
			 extend: 'Ext.data.Model',
			 fields:[
			 {name:'id',type:'long'},
			 {name:'regionCode',type:'String'},
			 {name:'name',type:'string'}
			 ]
});
var zoneGroupStore=Ext.create('Ext.data.Store',{
    model: 'ZoneGroup',
    proxy: new Ext.data.proxy.Ajax({
    	url: path+'/../../sc/zoneGroup!getAllZoneGroups.action',
		reader: {
            type: 'json',
            root: 'resultObject',
            totalProperty: 'resultObject.totalCount'
      }
    })
});
zoneGroupStore.load();
/*var zoneGroupCombo = Ext.create('Ext.form.ComboBox', {
	fieldLabel : i18n._('Release zoneGroup'),//发布位置
	width : 220,
	listConfig:{maxHeight:200},
	editable : false,
	allowBlank:false,
	emptyText:i18n._('Please Select'),
	store : zoneGroupStore,
	queryMode : 'local',
	forceSelect:true,
	displayField : 'name',
	valueField : 'regionCode'
});*/
var network_vlan_id_text=Ext.create('Ext.form.field.Display',{
	hidden:true,
});
var network_vlan_id=Ext.create('Ext.form.field.Number',{
    name: 'vlan_id',
    fieldLabel: i18n._('VLANID'),//'地址网段',
    minValue:1,
    hidden:true,
    maxValue:4094,
    minValue:1,
    allowDecimals:false,
    regexText:i18n._('InvalidIP'),
    maxLength:20,
    width:235,
    listeners : {
		//当vlanid改变之后的如果不为空则验证vlan_id是不是已经有了
		change  : function() {
			if(this.value>0 && this.value<=4094){
				if (this.value != null) {
					Ext.Ajax.request({
								url : '../../../ip/vlanidIsAvailable.action',
								params : {
									vlanId : this.value
								},
								success : function(response) {
									if(response.responseText.indexOf("可以")==-1){
										flag=false;
										network_vlan_id_text.setValue(response.responseText);
									}else{
										flag=true;
										network_vlan_id_text.setValue('')
									}
									
								}
							});
				};
			}
		}
	}
});
//定义静态数据
var networkTypeData = [
                   ['FLAT','flat'],['VLAN','vlan']
              ];
//定义ComboBox 的数据源
var networkTypeStore = new Ext.data.SimpleStore({
          fields:['net_type_name','net_type'],
          data:networkTypeData
});

var networkTypeCombo= Ext.create('Ext.form.ComboBox', {
	fieldLabel : i18n._('network type'),//发布位置
	width : 220,
	listConfig:{maxHeight:200},
	editable : false,
	allowBlank:false,
	emptyText:i18n._('Please Select'),
	store : networkTypeStore,
	queryMode : 'local',
	forceSelect:true,
	displayField : 'net_type_name',
	valueField : 'net_type',
	listeners:{
		'change':function(){
			if(this.value=="vlan"){
				network_vlan_id.show();
				network_vlan_id_text.show();
			}else{
				network_vlan_id.hide();
				network_vlan_id_text.hide();
			}
		}
	}
});

var networkModel=Ext.define('BusiSubnet', {
    extend: 'Ext.data.Model',
    fields: [
		{name: 'id',  type: 'int'},
		{name: 'networkId',  type: 'int'},
		{name: 'name',  type: 'string'},
		{name:'gateway',type:'string'},
		{name: 'enableDhcp',  type: 'boolean', convert: convertboolean},
		{name: 'dns',  type: 'string'},
		{name: 'cidr',  type: 'string'},
		{name: 'AddNetworkSection',  type: 'string'},
		{name: 'regionCode',  type: 'string'}
	]
});

function tooltipRenderer(value,metedata,record,rowIndex,colIndex,store){
	 metedata.tdAttr = 'data-qtip="' + value + '"';
	 return value;
}

var network_columns=[{xtype:'rownumberer', width: 30},
                     {"text":i18n._('name'),dataIndex:"name",flex:1,renderer:tooltipRenderer,menuDisabled:true},
                     {"text":i18n._('zoneCode'),dataIndex:"regionCode",flex:1,renderer:tooltipRenderer,menuDisabled:true},
                     {"text":i18n._('AddressNetworkSection'),dataIndex:"cidr",flex:1,renderer:tooltipRenderer,menuDisabled:true},
                     {"text":i18n._('gateWay'),dataIndex:"gateway",flex:1,renderer:tooltipRenderer,menuDisabled:true},
                     {"text":'DNS',"dataIndex":"dns","flex":1,renderer:tooltipRenderer,menuDisabled:true},
                     {"text":i18n._('WhethertoopenDHCP'),dataIndex:"enableDhcp",flex:1,menuDisabled:true}
                     ];
                     
                     


var v_proxy=new Ext.create('Ext.data.proxy.Ajax',
							 {
							         type: 'ajax',
							         url : path+'/../../ip/subNet!pageSubnet.action',
							 		reader: {
							             type: 'json',
							 			root:'resultObject.result',
							 			totalProperty: 'resultObject.totalCount'
							         }
							 }
 );
 
 var v_store=Ext.create('Ext.data.Store', {
     pageSize:pageSize,
 	width:'100%',
 	remoteSort:true,
 	proxy:v_proxy
 });
 v_proxy.setModel(networkModel);
 v_store.load();

 var v_height = 25;
 var v_width = 290;
 var v_margin = '1px';
 
 Ext.define('textPanel',{
 	extend:'Ext.panel.Panel',
 	height:v_height,
 	width:v_width,
 	border:false,
 	//layout:'hbox',
 	style:{
 		marginTop:v_margin
 	},
 	items:[
 		{
 		xtype:'textfield',
 		enforceMaxLength:true,
 		width:235,
 		allowBlank:false,
 		maxLength:50,
 		fieldLabel:''
 		}]
 	
 });

 Ext.define('commonForm',{ 
 extend:'Ext.form.Panel',	
                     border: false,
                     items: [{
 					xtype:"fieldset",
 					border:true,
 					anchor:'100% 100%',
                     style:{
 					 marginLeft:"5px",
 					 marginRight:"5px",
                      marginTop:"5px"
 					}
 					}]

                    });
 
 
 Ext.define('commonWindow',{
	 extend:'Ext.window.Window',
	 title:i18n._('add resource'),
	 modal:true,
	 width: 600,
	 manageHeight:true,
	 resizable:false,
	 layout: 'anchor',
	 closable:false,
	 constrain:true
	 });
 
 var network_name=Ext.create('textPanel',{
	    allowBlank:false
	});
 network_name.getComponent(0).setFieldLabel(i18n._('name'));	
 
 var network_cidr=Ext.create('Ext.form.field.Text',{
	    name: 'network_cidr',
	    fieldLabel: i18n._('AddressNetworkSection'),//'地址网段',
	    allowBlank:false,
	    regex:/^([1-9][0-9]{0,1}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){2}(\.(0|[1-9][0-9]{0,1}|1\d\d|2[0-4]\d|25[0-5]))(\/([1-9]|[12][0-9]|3[012]))$/,//禁止输入空白字符
	    regexText:i18n._('InvalidIP'),
	    maxLength:20,
	    width:235
	});

 var network_gateWay=Ext.create('Ext.form.field.Text',{
	    name: 'network_gateWay',
	    fieldLabel: i18n._('gateWay'),//网关
	    allowBlank:false,
	    regex:/^([1-9][0-9]{0,1}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){2}(\.([1-9][0-9]{0,1}|1\d\d|2[0-4]\d|25[0-5]))$/,//禁止输入空白字符
	    regexText:i18n._('InvalidGateWay'),
	    maxLength:20,
	    width:235
	});	
 
 var network_dns=Ext.create('Ext.form.field.Text',{
	    name: 'network_dns',
	    fieldLabel: i18n._('DNS'),//网关
	    allowBlank:false,
	    regex:/^([1-9][0-9]{0,1}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){2}(\.([1-9][0-9]{0,1}|1\d\d|2[0-4]\d|25[0-5]))$/,//禁止输入空白字符
	    regexText:i18n._('InvalidDNS'),
	    maxLength:20,
	    width:235
	});	
 
 var network_default=Ext.create('Ext.form.field.Checkbox',{
	    name: 'network_default',
	    fieldLabel: i18n._('WhetherDefaultNet'),//'是否开启DHCP'
});	
 
 var networkForm = Ext.create('commonForm');		
 networkForm.getComponent(0).setTitle(i18n._('Subnetinformation'));   //Subnetinformation
 networkForm.getComponent(0).add([/*zoneGroupCombo,*/networkTypeCombo,network_name,network_cidr ,network_gateWay,network_dns, {
	border:false,
	 layout:'column', // 从左往右的布局
     items:[network_vlan_id,  network_vlan_id_text]},{
		xtype : 'fieldcontainer',
		layout : 'hbox',
		items : [ network_default,{
			xtype : 'displayfield',
			margin:'0 5 0 25',
			width : 270,
			value : i18n._('缺省网络只能有一个，用于创建云主机的缺省外网')//请根据下拉列表选择所需处理器规格
		} ]
	},]);
 
 var addButton=Ext.create('Ext.button.Button',{
			 style:'margin-right:5',
			 text: i18n._('Add')
 });
 
var commonWindow=Ext.create('commonWindow', {
			                   constrain:true,
			 	            	tools:[{
			 	                type:'close',
			 	                handler:function(){					
			 					commonWindow.getComponent(0).getForm().reset();
			 					commonWindow.hide();
			 	                }
			 	                }],               
			                     buttons: [
			 					addButton,
			 					{   
			 					    style:'margin-right:5',
			                         text: i18n._('reset'),
			 						handler:function(){
			 						    commonWindow.getComponent(0).getForm().reset();
			 						}
			                     }]
});

function setUrl(rightUrl, url) {
	if(rightUrl == '') {
		rightUrl = url;
	}
	return rightUrl;
}

function refreshLeftTree(){
	
	 Ext.Ajax.request(  {
	         url: path+'/../../admin_mgmt/menu!getAdminMenu.action',
	         params:{
	             "parentId": 5
	         },
	         success:function(response){
	             var menuList = new Ext.JSON.decode(response.responseText);
	             var rightUrl = '';
	             var node = new Array();
	             for(var i = 0; i< menuList.length; i++) {
	           	 	node[i] = { text: i18n._(menuList[i].name),qtip:i18n._(menuList[i].name), leaf: false,href:decodeURIComponent(menuList[i].url),hrefTarget:'myframe',icon:menuList[i].icon, expanded: true};
	           	 	rightUrl = setUrl(rightUrl, decodeURIComponent(menuList[i].url));
	           	 	if(menuList[i].childrenList != null) {
	           	 		node[i].children = new Array();
	           	 		for(var j = 0; j < menuList[i].childrenList.length; j++) {
	           	 			node[i].children[j] = { text: i18n._(menuList[i].childrenList[j].name),qtip:i18n._(menuList[i].childrenList[j].name), leaf: true,href:decodeURIComponent(menuList[i].childrenList[j].url),hrefTarget:'myframe',icon:menuList[i].childrenList[j].icon};
	           	 			rightUrl = setUrl(rightUrl, decodeURIComponent(menuList[i].childrenList[j].url));
	           	 		}
	           	 	}
	             } 
	             /*
	             var result = {
	          	           		expanded: true,
	          	           		children: node
	          	       		  } ;
	          	  		
	             console.log(result);
	             console.log(parent.store_vm);
	             console.log(parent.store_vm.tree);
	             */
	             //console.log(parent.store_vm.getRootNode()); //"removeAll" "removeChild" "replaceChild"
	             parent.store_vm.getRootNode().removeAll() ;
	             parent.store_vm.getRootNode().appendChild(node);
	      }
      }
  );
}

//refreshLeftTree() ;

function ajax_request(v_json){
	if(!flag){
		return;
	}
	//alert(zoneGroupCombo.getValue())
	var v_mask = new Ext.LoadMask(Ext.getBody(), {
	                        msg: i18n._('saving'),
							//msg:i18n._('ServiceCatalog is saving,please wait!'),
	                        removeMask: true //完成后移除
	                    });
					v_mask.show();					
					Ext.Ajax.request({
						url: path+'/../../ip/subNet!saveSubnet.action'/*?regionCode=+zoneGroupCombo.getValue()*/,
						jsonData:v_json,
						success:function(response){
							v_mask.hide();
							commonWindow.hide();
							commonWindow.removeAll(false);
           					var result=Ext.JSON.decode(response.responseText);
           					if(result.success==false){
           						Ext.MessageBox.show({
 	                              // title: '提示',
                                    title:i18n._('notice'),
 	                               msg: result.resultMsg,
 	                               icon:Ext.MessageBox.INFO,	 	           		  
 	                               buttons: Ext.MessageBox.OK	 	                      
 	           				});
           					}else{
							    v_store.load();
							    refreshLeftTree() ;
							}
						}	
					});	
					commonWindow.getComponent(0).getForm().reset();
};

function showMsg(msg){
	 Ext.MessageBox.show({
        title: i18n._('Prompt'),
         msg: msg==null?i18n._('Input error'):msg,
       icon:Ext.MessageBox.INFO,
      buttons: Ext.MessageBox.OK
      });
}

function showWindow(){
	var Addsubnets = i18n._('Addsubnets');
	addButton.setText(i18n._('Add'));
	commonWindow.setTitle(Addsubnets);
	commonWindow.removeAll(false);
		commonWindow.add([networkForm]);
		addButton.setHandler(
			function(){
				if(!commonWindow.getComponent(0).getForm().isValid()){return;}
				if(networkTypeCombo.getValue()=="vlan"){
					if(!network_vlan_id.getValue()){
						network_vlan_id_text.setValue("VLAN模式下，请输入vlan id");
						return;
					}
				}
				if(removeAllSpace(network_name.getComponent(0).getValue())==""){
					 Ext.MessageBox.show({
						   title: i18n._('notice'),
						   msg:i18n._('ChildnetCannotBeSpaceOnly'),
                           icon:Ext.MessageBox.WARNING,
                           buttons: Ext.MessageBox.OK
					}); 
					return;
				}
				/* if(network_dns.getComponent(0).getValue()){
					var dnsArr=network_dns.getComponent(0).getValue().split(',');
					for(var i=0;i<dnsArr.length;i++){
						var ipReg=/^([1-9][0-9]{0,1}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){2}(\.([1-9][0-9]{0,1}|1\d\d|2[0-4]\d|25[0-5]))$/;
						if(!ipReg.test(dnsArr[i])){
							showMsg("DNS输入不合法，请重新输入。");
							return;
						}
					}
				} */
				var v_json={
						    cidr:network_cidr.getValue(),
						    vlanId:network_vlan_id.getValue(),
						    netType:networkTypeCombo.getValue(),
						    dns:network_dns.getValue(),
						    defaultNet:network_default.getValue(),							
						    gateway:network_gateWay.getValue(),
						    name:network_name.getComponent(0).getValue()
						};
				ajax_request(v_json);		
			}
		);
		commonWindow.show();
}
		 
		 Ext.QuickTips.init();
		 Ext.form.Field.prototype.msgTarget = 'side';
		 var pluginExpanded = true;
		 var dataGrid=Ext.create('Ext.grid.Panel', {
		     layout:'fit',
		 	title:i18n._('CMDB')+'  >  '+i18n._('IPManagement'),
		     store: v_store,
		 	simpleSelect:true,	
		 	sortableColumns:false,
		     columns: network_columns,
		 	selModel: Ext.create('Ext.selection.RowModel'),
		     //selType: 'rowmodel',
		 	bbar: Ext.create('Ext.PagingToolbar', {
		           store:v_store ,
		           displayInfo: true
		     }),
		     dockedItems:[
		      			{xtype:'toolbar',
		      			dock: 'top',
		      			//style:'background-color:#4c4c4c !important; background-image:url() !important;',
		      			cls: 'toolbarCSS',
		      			items:[{
		      				xtype:'button',
		      				margin:'0 0 0 0',
		      				icon:'../../../images/add_new.png',
		      				text:'<font id="AddNetwork" color="white" >' +i18n._("Add") + '</font>',
		      				 listeners: {
		    					 "mouseout" : function() {
		    						 document.getElementById("AddNetwork").style.color = "white";
		    					 },
		    					 "mouseover" : function() {
		    						 document.getElementById("AddNetwork").style.color = "black";
		    					 }
		    						
		    				 },
		      				handler:showWindow
		      			},
		      			{
		                      itemId: 'removeButton',
		                      text:'<font id="deleteNetwork" color="white" >' +i18n._("delete") + '</font>',
			      				listeners: {
			    					 "mouseout" : function() {
			    						 document.getElementById("deleteNetwork").style.color = "white";
			    					 },
			    					 "mouseover" : function() {
			    						 document.getElementById("deleteNetwork").style.color = "black";
			    					 }
			    						
			    				},
		                      icon: '../../../images/delete.png',
		      				handler:function(){
		      				var rows=dataGrid.getSelectionModel().getSelection();
		      				 var scId;
		      				 if(rows.length > 0){
		      				 scId=rows[0].get('id');
		      				 
		      				 Ext.MessageBox.show({
		      							    title: i18n._('notice'),
		      								msg:i18n._('Are you sure to delete'),
		      			                   buttons: Ext.MessageBox.YESNO,
		      			                   icon: Ext.MessageBox.QUESTION,
		      			                   fn:function(e){
		      			                	   if(e=="no"){
		      			                		   return;
		      			                	   }else if(e=='yes'){
		      			                		   Ext.Ajax.request({
		      											url: path+'/../../ip/subNet!deleteSubnet.action',
		      											method: 'POST',
		      											params:{
		      												'subnetId':scId
		      											},
		      											success:function(response){
		      					           					var result=Ext.JSON.decode(response.responseText);
		      					           					if(result.success==false){
		      					           						Ext.MessageBox.show({
		      				                                        title:i18n._('notice'),
		      					 	                               msg: result.resultMsg,
		      					 	                               icon:Ext.MessageBox.INFO,	 	           		  
		      					 	                               buttons: Ext.MessageBox.OK	 	                      
		      					 	           				});
		      					           					}else{
		      					           						Ext.MessageBox.show({
		      														  title: i18n._('notice'),
		      														 msg:i18n._('delete successfully'),
		      				                                          icon:Ext.MessageBox.INFO,
		      				                                          buttons: Ext.MessageBox.OK
		      				           
		      														});
		      					           					v_store.loadPage(1,null);
		      					           					refreshLeftTree() ;
		      												}
		      											}
		      												});
		      			                	   }
		      			                	 
		      			                	}
		      			    		});	 	
		      					}else{
		      						 Ext.MessageBox.show({
		      							    title: i18n._('notice'),
		      							    msg:i18n._('please choose one column'),
		                                      icon:Ext.MessageBox.WARNING,
		                                      buttons: Ext.MessageBox.OK
		      						}); 
		      						return;
		      			    	}		           
		      			        }
		                  }
		                  /*
		                  ,
		      			{xtype:'tbfill'},
		      			{
		    				xtype:'displayfield',
		    				hideLabel:true,
		    				value:'<span style="bottom:3px;position:relative;"><font color="white">'+i18n._('QuickSearch')+':'+'</font></span>'
		    			}
		      			,
		    			{    
		    				xtype: 'searchfield',
		    			    hideLabel:true,
		    				hasSearch:true,
		    				emptyText:i18n._('name'),
		    				store: v_store
		    			}
		      			*/
		      			]}],
		     width: '100%'
		     
		 });
		 
		 Ext.create('Ext.Viewport',{
			 layout:'fit',
			 items: dataGrid
			});
 
 
/*********************************************页面渲染结束******************************************************************/

						}
					};
				})();
				MultiLang.init();
});
	
	 function getCookie(name){
         var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
         if(arr != null) return unescape(arr[2]);
		 return null;
     }
</script>
</head>
<body>
</body>
</html>
